<template>
  <div>
    <!-- 还有一部分逻辑有问题，需要重新梳理一下 -->
    <div class="tools">
      <el-button @click="addChapter">添加章</el-button>
      <!-- <el-upload
        class="upload-demo"
        action="https://jsonplaceholder.typicode.com/posts/"
        :show-file-list="false"
      >
        <el-button type="primary">点击上传</el-button>
      </el-upload> -->
      <big-file-uploader></big-file-uploader>
      <el-button
        @click="saveChapterData"
        type="primary"
        :disabled="!chapterDataIsChange"
        >保存</el-button
      >
    </div>
    <!-- 章节 -->
    <el-tree
      :data="data"
      ref="tree"
      node-key="id"
      :props="defaultProps"
      @node-click="handleNodeClick"
      @node-contextmenu="handleNodeRightClick"
      :expand-on-click-node="false"
      :default-expand-all="true"
      :highlight-current="true"
      icon-class="el-icon-s-promotion"
    >
    </el-tree>

    <!-- 右键菜单 -->
    <vue-context-menu
      :contextMenuData="contextMenuData"
      @append="append"
      @edit="edit"
      @remove="remove"
    >
    </vue-context-menu>

    <!-- 添加章节时的对话框 -->
    <el-dialog title="请输入章节名称" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="章节名称" label-width="80">
          <el-input
            ref="input"
            v-model="form.chapterName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// TODO:标题的子标题，这个感觉应该不受限制，而不能只支持二级，但是可以只显示二级
import BigFileUploader from "@/components/BigFileUploader.vue";
import { Message } from "element-ui";
export default {
  name: "TeacherChapter",
  components: { BigFileUploader },
  data() {
    return {
      data: [],
      chapterDataIsChange: false,
      defaultProps: {
        children: "children",
        label: "label",
      },
      dialogFormVisible: false,
      form: {
        chapterName: "",
      },
      popVisible: false,
      contextMenuData: {
        menuName: "demo",
        // 菜单显示的位置
        axis: {
          x: null,
          y: null,
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: "append", // 绑定事件
            icoName: "el-icon-plus", // 图标 (本文取自 element-ui)
            btnName: "新增", // 菜单名称
          },
          {
            fnHandler: "edit",
            icoName: "el-icon-edit-outline",
            btnName: "编辑",
          },
          {
            fnHandler: "remove",
            icoName: "el-icon-delete",
            btnName: "删除",
          },
        ],
      },
      currentNode: null,
      type: null,
    };
  },
  methods: {
    // 点击就会跳转
    handleNodeClick(data) {
      console.log("进入data", data.children);
      // 如果不存在data.children或者data.children为空数组，就说明是节点，那么就可以跳转
      if (data.children == undefined) {
        this.$router.push({
          name: "chapter_edit",
          query: {
            section_id: data.id,
          },
        });
      }
    },

    // 章节的三种操作
    append() {
      this.type = "append";
      this.dialogFormVisible = true;
    },

    remove() {
      // 这里不直接remove先做判断 当前删除的是根节点type
      // console.log(this.currentNode);

      if (!this.chapterDataIsChange) {
        this.chapterDataIsChange = true;
      }
      this.$refs.tree.remove(this.currentNode);
    },
    edit() {
      // 为表格赋值
      this.type = "edit";
      this.form.chapterName = this.currentNode.label;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },
    handleConfirm() {
      let chapterName = this.form.chapterName;
      if (chapterName.length === 0) {
        this.$message({
          type: "warning",
          message: "不能为空",
        });
        return;
      }
      if (this.type === "append") {
        // 如果是二级数据就报错
        if (this.currentNode.children == undefined) {
          alert("已经是子级章节了，无法添加子级章节！");
          return;
        }
        //获取form.chapterName并添加到那个中
        const fatherChapterTag = this.currentNode.id;
        const currentID = this.currentNode.children.length + 1;
        const newChild = {
          id: `${fatherChapterTag}-${currentID}`,
          label: chapterName,
        };
        if (!this.currentNode.children) {
          //如果data.chidrent为空
          this.$set(this.currentNode, "children", []);
        }
        this.currentNode.children.push(newChild);
      } else if (this.type === "edit") {
        this.currentNode.label = chapterName;
      }
      //关闭弹窗
      this.form.chapterName = "";
      this.dialogFormVisible = false;
      // 维护是否有修改
      if (!this.chapterDataIsChange) {
        this.chapterDataIsChange = true;
      }
    },
    handleNodeRightClick(event, data) {
      this.currentNode = data;
      const x = event.clientX;
      const y = event.clientY;
      this.contextMenuData.axis = { x, y };
    },
    //添加章的回调
    addChapter() {
      const currentChapterTag = this.data.length + 1;
      const newChapter = {
        id: `ch${currentChapterTag}`,
        label: "示例章节，右键我修改",
        children: [],
      };
      this.data.push(newChapter);
      //维护是否修改
      if (!this.chapterDataIsChange) {
        this.chapterDataIsChange = true;
      }
    },

    // 保存章节数据的回调
    saveChapterData() {
      // 将章节数据上传
      const { course_id } = this;
      this.$http
        .post(
          `${this.$reqPrefix}/setChapter`,
          {
            course_id,
            chapter_data: this.data,
          },
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
            },
          }
        )
        .then((res) => {
          this.$codeJudge(res.data.code, "保存成功", "保存失败");
        });
    },
  },
  mounted() {
    this.defaultContextMenu = document.oncontextmenu;
    document.oncontextmenu = function () {
      return false;
    };
    // const {course_id} = this.$store.state.studyAbout.course;
    this.course_id = this.$store.state.studyAbout.course.course_id;

    this.$http
      .get(`${this.$reqPrefix}/chapter?course_id=${this.course_id}`)
      .then((res) => {
        this.data = res.data.data.data || [];
      });
  },
  beforeDestroy() {
    if (this.chapterDataIsChange) {
      // 提示已自动保存
      this.saveChapterData();
      //提示已经自动保存了
      Message.warning("已为您自动保存数据！");
    }
    document.oncontextmenu = this.defaultContextMenu;
  },
};
</script>

<style lang="less" scoped>
.tools {
  display: flex;

  .el-button {
    margin-left: 20px;
  }
}

ul {
  margin: 0;
  padding: 0;
}

.el-tree {
  margin-top: 20px;
  // background: #eee;
  // border-radius: 10px;
  overflow: hidden;

  .custom-tree-node {
    display: flex;
    align-items: center;
    color: #131b26;
  }

  :deep(.el-tree-node__content) {
    height: 48px;
  }
}
</style>